//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by Tony-ztb on 15/12/15.
//  Copyright © 2015年 Tony-ztb. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {

    let webView = UIWebView()
    override func loadView() {
        view = webView
        // 设置代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "授权"
        
//        print(view)
        loadOAuthPage()
        setNavBar()
    }

    override func viewDidDisappear(animated: Bool) {
        // 视图完全销毁后 让弹框也销毁掉
        SVProgressHUD.dismiss()
    }
    
    // MARK: 加载授权页面
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        
        webView.loadRequest(NSURLRequest(URL: url!))
    }
    
    // MARK: 设置导航条信息
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeOauth")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
    }
    
    @objc private func closeOauth() {
        // 关闭modal
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func defaultAccount() {
        
        // webView用js的方法 设置自动登陆
        
        let jsString = " document.getElementById('userId').value = '17703595175', document.getElementById('passwd').value = 'ZTB1028bin' "
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 协议方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

//        let urlString = request.URL?.absoluteString
        // 根据请求的url,去屏蔽不需要加载的页面
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        
        if !urlString.hasPrefix("http://www.baidu.com") {

            return false
        }
        
//        print(urlString)
        // 解析字符串获取code码
        // 获取到url中参数部分的键值
        let query = request.URL?.query
        
        if let q = query {
            // 字符串截取操作
            let codeStr = "code="
            let code = q.substringFromIndex(codeStr.endIndex)
            // 加载token
            loadAccessToken(code)
            
//            print(code)
        }
        
        return true
    }
    
    
    private func loadAccessToken(code: String) {
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                // 登录成功后 发出切换界面 的通知(先跳转到 欢迎界面, 再跳转到首页)
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    // 等modal出来的页面 被彻底回收后   再发送切换页面的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                })
                
                // 关闭modal
                // 这个方法是控制器 dismiss掉的   但是并不会立即被回收
//                self.close()
            } else {
                print("失败")
            }
        }
        
    }
 
}

